<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input v-model="queryParams.keyword" style="margin-bottom:10px" type="text" prefix-icon="el-icon-search" size="small" placeholder="输入员工姓名全员搜索" @input="ChangeValue" />
        <!-- 树形组件 -->
        <el-tree
          ref="tree"
          node-key="id"
          :data="depts"
          :props="defaultProps"
          default-expand-all
          :expand-on-click-node="false"
          highlight-current
          @current-change="ChangeId"
        />
      </div>
      <div v-loading="loading" class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-permission="'add-employee'" size="mini" type="primary" @click="$router.push('/employee/detail/')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <el-button size="mini" @click="getExcel">excel导出</el-button>
        </el-row>
        <el-table :data="tableData">
          <el-table-column prop="staffPhoto" align="center" label="头像">
            <template #default="{ row }">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" />
              <span v-else class="username">{{ row.username?.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template #default="{ row }">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作" width="280px">
            <template #default="{ row }">
              <el-button size="mini" type="text" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button size="mini" type="text" @click="showrole(row.id)">角色</el-button>
              <el-popconfirm title="确认删除该条数据吗？" @onConfirm="delEmployee(row.id)">
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>
              <!-- <el-popconfirm
                title="这是一段内容确定删除吗？"
              >
                <el-button slot="reference">删除</el-button>
              </el-popconfirm> -->
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination
            layout="total,prev, pager, next"
            :total="total"
            :page-size="queryParams.pagesize"
            :current-page="queryParams.page"
            @current-change="ChangePage"
          />
        </el-row>
        <!-- 表格组件 -->
        <!-- 分页 -->
      </div>
    </div>
    <importExcel :show-excel-dialog.sync="showExcelDialog" @uploadsuccess="getDepartment" />
    <!-- 分配角色的弹出层 -->
    <el-dialog
      title="提示"
      :visible.sync="roledialogshow"
    >
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="item in rolelist" :key="item.id" :label="item.id">
          {{ item.name }}
        </el-checkbox>
      </el-checkbox-group>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roledialogshow = false">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getDepartmentList } from '@/api/department'
import { listToTree } from '@/utils/listtotree'
import { delEmployee, getEmployeeList, getEnableRoleList, getEmployeeDetail, assignRole } from '@/api/employee'
import FileSaver from 'file-saver'
import importExcel from './components/import-excel.vue'
import { exportEmployee } from '@/api/employee'
export default {
  name: 'Employee',
  components: {
    importExcel
  },
  data() {
    return {
      depts: [], // 组织数据
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      // 发送请求时的参数
      queryParams: {
        departmentId: null, // 部门id
        page: 1, // 页码
        pagesize: 8, // 每页条数
        keyword: '' // 关键字
      },
      total: 0, // 总条数
      // 右侧表格数据
      tableData: [],
      timer: null, // 防抖定时器
      showExcelDialog: false, // 是否显示导入excel弹窗
      roledialogshow: false, // 是否显示分配角色的弹窗
      roleIds: [], // 选中角色id数组
      rolelist: [], // 角色列表
      userId: null,
      loading: false
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    async getDepartment() {
      // 递归方法 将列表转化成树形
      // let result = await getDepartment()
      const res = await getDepartmentList()
      console.log(res)
      this.depts = listToTree(await getDepartmentList(), 0)
      this.queryParams.departmentId = this.depts[0].id
      // 默认选中第一项并添加高亮效果
      // 注意：tree组件的渲染是异步的这里需要用到nextTick
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(this.queryParams.departmentId)
      })
      this.getEmployeeList()
    },
    // 获取员工列表
    async getEmployeeList() {
      const res = await getEmployeeList(this.queryParams) // 发送请求
      console.log(res)
      this.tableData = res.rows // 更新数据
      this.total = res.total // 更新总条数
    },
    // 选中的节点发生变化时触发
    ChangeId(node) {
      this.queryParams.departmentId = node.id
      this.queryParams.page = 1 // 重置页码
      this.getEmployeeList() // 重新请求数据
    },
    // 页码发生变化时触发
    ChangePage(page) {
      this.queryParams.page = page // 更新页码
      this.getEmployeeList() // 重新请求数据
    },
    // 模糊搜索
    // 模糊搜索
    ChangeValue() {
      // 使用防抖进行性能优化
      clearTimeout(this.timer) // 清除定时器
      this.timer = setTimeout(() => {
        this.queryParams.page = 1 // 重置页码
        this.getEmployeeList() // 重新请求数据
      }, 500) // 设置定时器
    },
    // 导出excel
    async getExcel() {
      const res = await exportEmployee() // 发送请求
      console.log(res)
      FileSaver.saveAs(res, '员工数据.xlsx') // 保存文件
    },
    // 删除员工
    async delEmployee(id) {
      await delEmployee(id) // 发送请求
      this.$message.success('删除成功') // 提示用户
      if (this.depts.length === 1) {
        this.queryParams.page--
      }
      this.getEmployeeList() // 重新请求数据
    },
    async showrole(id) {
      this.loading = true // 显示加载中
      // 显示弹层
      // this.roledialogshow = true
      // 获取角色列表
      const res = await getEnableRoleList()
      this.rolelist = res // 赋值角色列表
      this.userId = id // 赋值用户id
      const { roleIds } = await getEmployeeDetail(id) // 获取已选中的角色id
      this.roleIds = roleIds // 赋值
      this.loading = false // 隐藏加载中
      // 注意要在数据请求完成后再显示弹层
      this.roledialogshow = true
    },
    // 确定分配
    async confirm() {
      await assignRole({
        id: this.userId,
        roleIds: this.roleIds
      })
      this.$message.success('分配成功')
      this.roledialogshow = false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}

</style>
